<!-- 在这个文件对每个tab对应的列表进行渲染 -->
<template>
	<view class="item-container">
		<!-- 这里设置了z-paging加载时禁止自动调用reload方法，自行控制何时reload（懒加载）-->
		<!--  :enable-back-to-top="currentIndex===tabIndex" 在微信小程序上可以多加这一句，因为默认是允许点击返回顶部的，但是这个页面有多个scroll-view，会全部返回顶部，所以需要控制是当前index才允许点击返回顶部 -->
		<z-paging ref="paging" v-model="dataList" @query="queryList" @scroll="pageScrollFn" :hide-no-more-inside="true" :fixed="false" :auto="true">
			<!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
			<template #refresher="{refresherStatus}" style="height: 200rpx;">
						<!-- 此处的custom-refresh为demo中自定义的组件，非z-paging的内置组件，请在实际项目中自行创建。这里插入什么view，下拉刷新就显示什么view -->
				<image src="/static/home/refreshLoading.gif" mode="heightFix" style="height: 100rpx;margin: 0 auto;display: block;"></image>
				<view class="u-text-center">{{statusTextArr[refresherStatus]}}</view>
			</template>
			<!-- 自定义没有更多数据view -->
			<template #loadingMoreNoMore>
				<view class="u-flex u-col-center u-row-center">
					<u-line color="#DFDFDF" length="110rpx"/>
					<view class="u-flex u-m-l-30 u-m-r-30" style="flex-direction: column;align-items: center;">
						<image src="/static/home/noMore.png" mode="heightFix" style="height:50rpx;margin: 0 auto;display: block;"></image>
						<text class="u-font-10 u-m-t-6" style="color:#999">没有更多了</text>
					</view>
					<u-line color="#DFDFDF" length="110rpx"/>
				</view>
			</template>
			<template #top>
					<view >
						<view class="filter-container" >
							<view class="filter-top u-flex u-row-between  u-p-l-30 u-p-r-30 u-font-28">
								<view style="flex:1;overflow: hidden;">
									<u-tabs class="owner-tab" :offset="[6,-40]"
									:isFilterMenu="true" 
									:list="groupList" 
									active-color="#ff551a" :is-scroll="groupList.length>3" :showBadge="false" :current="collectCurrent" @change="groupChange"></u-tabs>
								</view>
								
								<view  class="u-flex "  @click="$mRouter.push({route:'/pages/sale/homePage/GroupManger'})">
									<view class="u-m-r-10 u-p-l-20" style="border-left: 1px solid #e3e3e3;">管理</view>
									<view class="u-flex" style="flex-direction: column;">
										<view class="iconfont icon-shaixuan1"></view>
									</view>
								</view>
							</view>
							
						</view>
					</view>
			</template>
		
			<view class="item-content u-p-t-20">
				<u-checkbox-group  :wrap="true" :size="40" :icon-size="20" :label-disabled="true" shape="circle" :active-color="themeColor">
					<u-checkbox 
						:labelClass="true"
						@change="checkboxChange" 
						v-model="item.checked" 
						v-for="(item, index) in dataList" :key="item.id" 
						:name="index"
						style="width: 100%;"
					>
					 <!-- v-for="(item,index) in dataList" :key="index" @click="itemClick(item)" -->
					<view class="item-list u-m-b-20  u-flex" @click="itemClick(item)">
						<div class="" style="position: relative;">
							<image :src="item.resourceUrl" mode="" class="item-image u-m-r-14 u-m-l-10"></image>
							<view class="not-buy u-flex u-row-center u-m-r-14 u-m-l-10" v-if="item.buyItemReason!==0">
								<view class="not-buy-reason"> {{item.buyItemReasonString}} </view>
							</view>
						</div>
						<view class="item-info">
							<view class="u-flex u-row-between " style="flex-direction: column;height: 100%;line-height: normal;" >
								<view style="width: 100%;" >
									<view class="u-flex u-col-top">
										<view :class="['item-name','u-line-2',{'grey-color':item.buyItemReason!==0}]" style="flex:1;">{{item.itemName}}</view>
										<!--  -->
										<view class="iconfont icon-del" style="font-size: 40rpx;color:#333;" @click.stop="delItemOneFn(item.itemId)"></view>
										<!-- <u-icon name="trash"   color="#999" size="50" class="u-m-l-20"></u-icon> -->
									</view>
									<view class="item-val  u-m-t-6 u-m-b-6" :style="{'border': item.buyItemReason!==0?'1px solid #999':'1px solid #FF551A'}">
										<view :class="['item-val-text','item-val-specifica-title',{'item-val-title-not-buy':item.buyItemReason!==0}]">规格</view>
										<view :class="['item-val-text','item-val-specifica-text',{'item-val-not-buy':item.buyItemReason!==0}]">{{item.specification}}</view>
									</view>
									<br />
									<view class="item-val u-line-1" :style="{'border': item.buyItemReason!==0?'1px solid #999':'1px solid #C09A87'}" >
										<view :class="['item-val-text','item-val-owner-title',{'item-val-title-not-buy':item.buyItemReason!==0}]">品牌商</view>
										<view :class="['item-val-text','item-val-owner-text',{'item-val-not-buy':item.buyItemReason!==0}]">{{item.brandOwnerName}}</view>
									</view>
									<!-- <view class="item-stock u-font-24">库存{{item.inventoryBalance}}{{item.unit||'瓶'}}</view> -->
									
								</view>
								<view class="u-flex u-row-between u-col-bottom " style="width: 100%;">
									<view class="u-flex u-col-bottom">
										<view class="item-price u-font-28 " style="font-weight: 500;">
											<text  v-if="item.buyItemReason!==0"  style="color: #999;">{{item.buyItemReasonString}}</text>
											<text v-else style="color: #FF551A;">￥{{item.currentPrice}}</text>
										</view>
										<view class="item-price u-font-28 " v-if="item.diffPrice!=0" style="color: #ADADAD;font-weight: 400;">
											<s>{{item.collectingPrice?'￥'+item.collectingPrice:'未定价'}}</s> 
										</view>
										<text class="iconfont icon-rise u-m-l-10" 
										v-if="item.diffPrice!=0"
										:style="{
											color:item.diffPrice>0?'#FF551A':'#21AD00',
											transform:item.diffPrice>0?'':'rotateY(180deg)'
											}"></text>
									</view>
									<view :class="['item-add', 'u-flex', 'u-row-center',{'item-no-add':item.buyItemReason!==0}]"   @click.stop="addItemFn(item)" 
									>
										<view class="u-font-22">加购</view>
										<u-icon name="plus" color="#C88D00" size="18"></u-icon>
									</view>
								</view>
							</view>
						</view>
					</view>
				</u-checkbox>
				</u-checkbox-group>
			</view>
			<template #bottom>
				<view class="u-p-30 u-flex u-row-between " style="border-top: 1px solid #eee;">
					<view class="u-flex">
						<u-checkbox class="u-flex" :icon-size="20" :size="40" :name="'全选'" v-model="allSelect" shape="circle" label-size="24rpx" :active-color="themeColor" @change="checkedAll">
							<text style="font-weight: bolder;">全选</text>
						</u-checkbox>
						<view v-if="chooseList.length">已选{{chooseList.length}}个</view>
					</view>
						
					<view class="u-flex">
						<button type="default" class="group-btn u-m-r-10" @click="delItemTap()">移除收藏</button>
						<button type="default" class="group-btn" @click="moveItemTap()">移至分组</button>
					</view>
				</view>	
			</template>
			
		</z-paging>
		<u-mask :show="showChoseNum" :z-index="888" :custom-style="{background: 'rgba(0, 0, 0, 0.3)'}" @click="showChoseNum = false"></u-mask>
		<view v-if="showChoseNum" class="chose-num box-padding">
			<view class="u-flex u-row-between" style="height: 111rpx; padding-bottom: 20rpx;">
				<text class="text-bold">下单数量</text>
				<number-box box-width="100rpx" width="200rpx" height="50rpx" fontSize="28rpx"
				 :value="quantity"
				  :step="product.sellingUnit?product.sellingUnit:1" 
				  :min="product.sellingUnit?product.sellingUnit:1" 
				  :max="product.inventoryBalance" 
				  @change="updateQuantity"></number-box>
			</view>
			<view class=" u-m-b-30 sellunit-box">
				最小销售单位 {{product.sellingUnit}}  {{product.unit||'瓶'}}
			</view>
			<u-button shape="circle" hover-class="none" :ripple="true" :hair-line="false" :custom-style="getBtStyle('default')" @click.native="AddCartFn">加入购物车</u-button>
		</view>
		<view :class="['shop-cart-container',transformClass?'shop-cart-active':'']" @click="goShopCartFn">
			<u-icon name="shopping-cart" style="font-size: 60rpx;font-weight: bold;"></u-icon>
		</view>
		<u-action-sheet v-if="chooseGroupShow" :list="groupShowList" @click="moveItemFn" safe-area-inset-bottom	 v-model="chooseGroupShow"></u-action-sheet>
		<u-modal v-model="delModelShow" confirm-color="#ff551a" @confirm="delGroupItemFn" :content="'您确定要从收藏中移除商品吗？'" title="注意"></u-modal>
	</view>
</template>

<script>
	import NumberBox from '@/components/number-box/index.vue';
	import { useUserStore } from '@/store/user.js';
	import { useShopStore } from '@/store/shop.js';
	import { mapState } from 'pinia';
	export default {
		components:{ NumberBox },
		data() {
			return {
				//v-model绑定的这个变量不要在分页请求结束中自己赋值！！！
				delModelShow:false,
				chooseGroupShow:false,
				groupShowList:[],
				dataList: [],
				isShowBuy:true,
				showChoseNum:false,
				product:{},
				quantity:1,
				timer:null,
				transformClass:true,
				statusTextArr: ['哎呀，用点力继续下拉！', '拉疼我啦，松手刷新~~', '正在努力刷新中...', '刷新成功啦~'],
				groupList:[
					{
						name:'默认',
						id:"default-group"
					}
				],
				collectCurrent:0,
				chooseGroupId:"default-group",
				allSelect:false,
				delGroupItemIds:[],
			}
		},
		props:{
			SellerId:{
				type:String,
				default:""
			},
			keyWords:{
				type:String,
				default:""
			},
			searchBrand: {
				type: Array,
				default () {
					return []
				}
			},
			searchClass: {
				type: Array,
				default () {
					return []
				}
			},
			searchOwner: {
				type: Array,
				default () {
					return []
				}
			},
			startPrice:'',
			endPrice:'',
			SortBy:{
				type:Number,
				default:0
			}
		
		},
		created(){
			// this.$refs.paging.reload();
			this.getGroupList()
		},
		onShow() {
			this.collectCurrent = 0;
			this.getGroupList();
		},
		computed:{
			chooseList(){
				return this.dataList.filter(item=>{return item.checked});
			},
			...mapState(useUserStore,['isPurchase','isReceive']),
			...mapState(useShopStore, {storeShop: 'shop'})
		},
		methods: {
			moveItemTap(){
				if(this.chooseList.length==0){
					this.$u.toast('您还没有选择商品');
					return false;
				};
				this.groupShowList.map(item=>{
					if(item.id === this.chooseGroupId){
						item.color='#ff551a';
						item.disabled = true;
					}else{
						delete item.color
						delete item.disabled
					}
				})
				this.chooseGroupShow = true;
			},
			delItemOneFn(id){
				console.log(222);
				this.delGroupItemIds = [id];
				this.delModelShow = true;
			},
			delItemTap(){
				if(this.chooseList.length==0){
					this.$u.toast('您还没有选择商品');
					return false;
				};
				let ary = [];
				this.chooseList.forEach(item=>{
					ary.push(item.itemId)
				});
				this.delGroupItemIds = this.$u.deepClone(ary);
				this.delModelShow = true; 
			},
			async delGroupItemFn(){
				uni.showLoading({
					title:"删除中..."
				})
				let params = {
					groupId:this.chooseGroupId,
					ItemIds:JSON.parse(JSON.stringify(this.delGroupItemIds))
				}
				if (this.chooseGroupId === 'default-group') {
					delete params.groupId
				}
				const res = await this.$newHttp.delete('api/v1.2/Favorite/Remove?'+this.$mHelper.stringify(params));
				uni.hideLoading({
					title:"删除中..."
				})
				if(res.code === 200){
					uni.showToast({
						title:'删除成功'
					});
					this.$refs.paging.reload();
				}else{
					this.$u.toast('删除失败，错误信息：'+res.erroMessage);
				}
			},
			async moveItemFn(val){
				console.log(val);
				uni.showLoading({
					title:"移动中..."
				})
				let ary = this.chooseList.map(item => {
					return item.id //2023.07.21 与陈宇确认  使用ID 不是itemId  (已确认，做个备注)
				});
				let params = {
					collectItemIds: ary,
					groupId:this.groupShowList[val].id,
				}
				if (this.groupShowList[val].id === 'default-group') {
					delete params.groupId
				}
				const res = await this.$newHttp.put('api/v1.2/Favorite/MoveItemsToGroup',params);
				uni.hideLoading({
					title:"移动中..."
				})
				if(res.code === 200){
					uni.showToast({
						title:'移动成功'
					});
					this.$refs.paging.reload();
				}else{
					this.$u.toast('移动失败，错误信息：'+res.erroMessage);
				}
			},
			// 选中某个复选框时，由checkbox时触发
			checkboxChange(e) {
				this.dataList[e.name].checked = e.value;
				this.allSelect = this.dataList.every(item=>{return item.checked === true});
			},
			checkedAll(e) {
				this.dataList.map(val => {
					val.checked = e.value;
				});
			},
			async getGroupList(){
				const res = await this.$newHttp.get('api/v1.2/Favorite/GetAllGroups');
				if(res.code === 200){
					let ary = [{
						name:'默认',
						id:"default-group"
					}];
					if(res.data.length!=0){
						ary.push(...res.data);
					}
					this.groupList = ary;
					this.groupShowList = ary.map(item=>{
						return {
							text:item.name,
							id:item.id,
						}
					})
				}
			},
			groupChange(val){
				this.collectCurrent = val;
				this.chooseGroupId = this.groupList[val].id;
				this.$refs.paging.reload();
			},
			// 滚动隐藏购物车
			pageScrollFn(){
				this.transformClass = true; //要添加的class类名
				clearTimeout(this.timer);//这里必须要每次滚动前 清除一次
				// 如果停留则表示滚动结束  一旦空了1s就判定为滚动结束
				this.timer = setTimeout(() => {
				  this.transformClass = false //滚动结束清除class类名
				}, 1500);
			},
			async AddCartFn(){
				let params = {
					itemId: this.product.id,
					sellerShopId: this.SellerId,
					quantity: this.quantity,
					buyerShopId: this.storeShop.id,
				}
				uni.showLoading({
					title:'loading...'
				})
				const res = await this.$newHttp.post('api/ShoppingCart/AddShoppingCart', params);
				uni.hideLoading();
				if (res.code === 200) {
					this.$u.toast('添加成功', 1000, 'success');
					this.showChoseNum = false;
				}else{
					this.showChoseNum = false;
					this.$u.toast('添加失败，错误信息：'+res.erroMessage, 1000, 'failed');
				}
			},
			loadAgainFn(){
				console.log(this.startPrice);
				console.log(this.endPrice);
				if(this.startPrice>this.endPrice){
					this.$u.toast('价格区间筛选格式不正确，请输入正确的价格区间~');
					return false; 
				}
				this.$refs.paging.reload(); 
			},
			goShopCartFn(){
				if(!this.transformClass){
					if (!this.isPurchase) {
						return this.$u.toast('当前账号没有查看购物车的权限，请联系管理员处理~');
					}else{
						uni.navigateTo({
							url: '/pages/sale/homePage/shopCart',
						});
					};
				};
				this.transformClass = false;
			},
			addItemFn(item){
				if(item.buyItemReason!==0){
					return false;
				}
				if(!this.isPurchase){
					return this.$u.toast('当前账号没有下单的权限，请联系管理员处理~');
				}
				this.quantity = item.minimumPurchaseQuantity;
				// this.product = item;
				this.product = {
					id:item.itemId,
					sellingUnit:item.minimumPurchaseQuantity,
					inventoryBalance:item.inventoryBalance,
					unit:item.unit
				};
				this.showChoseNum = true;
			},
			// 修改数量
			updateQuantity(value) {
				this.quantity = value
			},
			async queryList(pageNo, pageSize) {
				//组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				//这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				//模拟请求服务器获取分页数据，请替换成自己的网络请求
				const params = {
					pageIndex: pageNo,
					pageSize: pageSize,
					BuyerId:this.storeShop.id,
					SellerId:this.SellerId,
					// Purchasable:this.isShowBuy,
					groupId:this.chooseGroupId
				}  
				if (this.chooseGroupId === 'default-group') {
					delete params.groupId;
				}
				uni.showLoading({
					title: 'loading...',
					mask: false
				});
				const res = await this.$newHttp.get('api/v1.2/Favorite/GetCollectItemsByPage',{params:params});
				uni.hideLoading({
					title: 'loading...'
				})
				if(res.code === 200){
					let ary = res.data.list.map(item=>{
						item.checked = this.allSelect;
						return item
					});
					this.$refs.paging.complete(ary);
				}else{
					this.$refs.paging.complete(false);
				}
			},
			itemClick(item) {
				console.log(item);
				let auth = item.isPurchasable?1:0;
				this.$mRouter.push({
					route: '/pages/index/xiangqing?id=' + item.itemId + '&sellerShopId=' + item.sellerId + '&auth=' +auth
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/iconfont/iconfont.css';
	/* 注意:父节点需要固定高度，z-paging的height:100%才会生效 */
	.item-container {
		height: 100%;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		background: #fff;
		::v-deep.z-paging-content{
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
		}
		.filter-container{
			background-color: #fff;
			
			height: 100rpx;
			width: 100%;
			
		}
		.item-content{
			box-sizing: border-box;
			padding: 0 34rpx;
			.item-list{
				background-color: #fff;
				border-radius: 20rpx;
				position: relative;
				
				.no-sign{
					width: 130rpx;
					height: 130rpx;
					position: absolute;
					top: 0;
					right: 0;
				}
				.item-image{
					width: 220rpx;
					height: 230rpx;
					border: 1px solid #E4E4E4;
					border-radius: 10rpx;
				}
				.not-buy{
					position: absolute;
					left: 0;
					top: 0;
					width: 220rpx;
					height: 230rpx;
					background-color: rgba(255, 255, 255, 0.6);
					.not-buy-reason{
						background: rgba(0,0,0,0.45);
						color: #DEDEDE;
						border-radius:25rpx;
						box-sizing: border-box;
						padding: 6rpx 20rpx;
						font-size: 24rpx;
					}
				}
				.item-info{
					flex:1;
					height: 232rpx;
					overflow: hidden;
					.item-name{
						font-weight: 500;
						font-size: 28rpx;
					}
					.item-val{
						display: inline-block;
						font-size: 20rpx;
						box-sizing: border-box;
						border-radius: 4px;
						line-height: normal !important;
						.item-val-text{
							display: inline-block;
							box-sizing: border-box;
							padding: 4rpx 8rpx;
						}
						.item-val-specifica-title{
							border-right: 1px solid #ff551a;
							background-color: #FFE1D6;
							color: #FF551A;
							border-top-left-radius: 4px;
							border-bottom-left-radius: 4px;
							font-size: 20rpx;
						}
						.item-val-specifica-text{
							color: #FF551A;
							font-size: 20rpx;
						}
						.item-val-owner-title{
							font-size: 20rpx;
							border-right: 1px solid #C09A87;
							background-color: #FAF1DF;
							color: #B88D77;
							border-top-left-radius: 4px;
							border-bottom-left-radius: 4px;
						}
						.item-val-owner-text{
							color: #B88D77;
							font-size: 20rpx;
						}
						.item-val-title-not-buy{
							background-color: #DEDEDE;
							color: #999;
							border-color: #999 !important;
						}
						.item-val-not-buy{
							color: #999;
						}
					}
					.item-price{
						font-weight: bold;
						color: #ff551a;
					}
					.item-stock{
						color: #999;
						font-size: 20rpx;
					}
					.item-add{
						background-color: #FFEEC7;
						border-radius: 24px;
						box-sizing: border-box;
						width: 100rpx;
						height: 49rpx;
						line-height: 49rpx;
						// padding:10rpx 20rpx;
						border: 1px solid #C88D00;
						color: #C88D00;
						font-size: 28rpx;
					}
					.item-no-add{
						color: #9D9D9D;
						background: #E7E7E7;
						border: 1px solid #9D9D9D;
					}
				}
				
			}
		}
		.group-btn{
			width: 166rpx;
			height: 66rpx;
			background: #FFBB1A;
			border-radius: 33rpx;
			font-size: 26rpx;
			font-weight: 400;
			color: #333;
			&::after{
				border: none;
			}
		}
		.chose-num {
			// height: 250rpx;
			width: 100%;
			position: fixed;
			bottom: 0;
			background-color: #FFFFFF;
			z-index: 999;
			box-sizing: border-box;
			padding-bottom: 20rpx;
			/* #ifdef APP-PLUS */
			padding-bottom: env(safe-area-inset-bottom);
			/* #endif */
			.sellunit-box{
				background-color: #f8f8f8;
				color:#999;
				box-sizing: border-box;
				padding: 20rpx 30rpx;
			}
		}
		.shop-cart-container{
			position: fixed;
			bottom: 200rpx;  
			right: 14rpx; 
			z-index: 887;
			width: 120rpx; 
			height: 120rpx; 
			border-radius: 50%; 
			background-color: #FFBB1A;
			display: flex;
			justify-content: center;
			align-items: center;
			box-shadow: 0px 0px 18px 2px rgba(6,0,1,0.1);
			transition: all 0.5s ease;
		}
		.shop-cart-active{
			right: -60rpx;
			opacity:0.4;
			transition: all 0.5s ease;
		}
	}


</style>
